package Controller;

import static DataAcces.DBAcces.*;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;


/**
 *
 * @author Promociones
 */
public class PackageManager {
    
    public static final String ArticleTable = "Articulo";
    static final String ColmNames = "Estado,Numero,Nombre_Consignatario,Descripción_de_Productos,Peso_lb,Piezas,Fecha_Entrada,Fecha_Salida,Numero_de_Seguimiento";
    
    public static void Limpiar(JTable Table,JComboBox Filtro,
                               JTextField BarCode,JTextField Warehouse,
                               JTextField Cliente,JTextField Descripcion,
                               JFormattedTextField Peso,JTextField Paquetes,
                               JTextField Buscar){
        GetReg(Table);
        Filtro.setSelectedIndex(0);
        BarCode.setText("");
        Warehouse.setText("");
        Cliente.setText("");
        Descripcion.setText("");
        Peso.setText("");
        Paquetes.setText("");
        Buscar.requestFocus();
    }
    
    public static void Buscar( JTable jTable1,JTextField Buscar,
                              JComboBox Filtro,JTextField Warehouse,
                              JTextField Cliente,JTextField Descripcion,
                              JFormattedTextField Peso,JTextField Paquetes,
                              JTextField BarCode){
        if(Buscar.getText().isEmpty()) {
           GetReg( jTable1);
        }else if (Filtro.getSelectedIndex() == 0 && !Buscar.getText().isEmpty()){
            if(Buscar.getText().length()==14){
                String Filter = "Numero = '" +Buscar.getText().substring(5, 11)+"'";
                GetRegister(ArticleTable, Filter, jTable1, ColmNames);
                SelectFind(jTable1, Buscar, Filtro, Warehouse, Cliente, 
                           Descripcion, Peso, Paquetes, BarCode);
                Guardar(jTable1, Warehouse, Cliente, Descripcion, Peso, 
                        Paquetes, BarCode,Filtro,Buscar);
            }
        }else if (Filtro.getSelectedIndex() == 1 && !Buscar.getText().isEmpty() 
                && IsNumeric(Buscar)){
            String Filter = "Numero = " +Buscar.getText();
            GetRegister(ArticleTable, Filter, jTable1, ColmNames);
            SelectFind(jTable1, Buscar, Filtro, Warehouse, Cliente, 
                           Descripcion, Peso, Paquetes, BarCode);
        }else if (!Buscar.getText().isEmpty() && Filtro.getSelectedIndex() == 2){
            String Filter = "Nombre_Consignatario like '%" + Buscar.getText()+"%'";
            GetRegister(ArticleTable, Filter, jTable1, ColmNames);
            SelectFind(jTable1, Buscar, Filtro, Warehouse, Cliente, 
                           Descripcion, Peso, Paquetes, BarCode);
        }else if (!Buscar.getText().isEmpty() && Filtro.getSelectedIndex() == 3){
            String Filter = "Descripción_de_Productos like '%" + Buscar.getText()+"%'";
            GetRegister(ArticleTable, Filter, jTable1, ColmNames);
            SelectFind(jTable1, Buscar, Filtro, Warehouse, Cliente, 
                           Descripcion, Peso, Paquetes, BarCode);
        }
    }
    
    public static void SelectFind(JTable jTable1,JTextField Buscar,
                                  JComboBox Filtro,
                                  JTextField Warehouse,JTextField Cliente,
                                  JTextField Descripcion,JTextField Peso,
                                  JTextField Paquetes,JTextField BarCode){
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            if(Buscar.getText().length()>11){
                if (jTable1.getValueAt(i, 1).equals(Buscar.getText().substring(5, 11)) && Filtro.getSelectedIndex()==0) {                                           
                    jTable1.getSelectionModel().setSelectionInterval(i, i);
                    GetFromtable(jTable1, Warehouse, Cliente, 
                                 Descripcion, Peso, Paquetes, BarCode);
                    break;
                }
            }else if (jTable1.getValueAt(i, 1).equals(Buscar.getText()) && Filtro.getSelectedIndex()==1) {                                           
                    jTable1.getSelectionModel().setSelectionInterval(i, i);
                    GetFromtable(jTable1, Warehouse, Cliente, 
                                 Descripcion, Peso, Paquetes, BarCode);
                    break;
                }
        }
    }
    
    public static void Guardar(JTable jTable1,JTextField Warehouse,
                               JTextField Cliente,JTextField Descripcion,JFormattedTextField Peso,
                               JTextField Paquetes,JTextField BarCode,JComboBox Filtro,
                               JTextField Buscar){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
            if( IsNumeric(Warehouse) && 
               !Warehouse.getText().isEmpty() &&
               !Cliente.getText().isEmpty() &&
               !Descripcion.getText().isEmpty() &&
               !Peso.getText().isEmpty() &&
               !Paquetes.getText().isEmpty()){
                if((ValidaRegistro(ArticleTable, Warehouse.getText(), "Numero",ColmNames) || 
                        ValidaRegistro(ArticleTable, "'"+BarCode.getText()+"'", "BarCode",ColmNames))){
                    if(jTable1.getSelectedRow()!= -1){
                        if( jTable1.getValueAt(jTable1.getSelectedRow(), 6).equals("")){
                            boolean Send = false;
                                DBDataUpdate(ArticleTable, "Fecha_Entrada = '"+dateFormat.format(new Date())+"',"
                                                            + "Estado = 'Almacen Genuine'", "'"+Warehouse.getText()+"'");
                                
                                String Cl = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 2));
                                String GP = Cl.substring(Cl.length()-5,Cl.length()); 
                                String UMail = "",UName="";
                                List CL = GetRegisterFiltered("Clientes", "Número_de_Cuenta = "+GP);
                                List AT = GetRegisterFiltered("Articulo", "numero = "+Warehouse.getText());
                                for(int a=0;a<CL.size();a++){
                                    Object[] Cliente2 = (Object[]) CL.get(a);
                                    Object[] Articulo = (Object[]) AT.get(a);
                                    
                                   
                                        //SendMail.SendMail("paqueteria@genuinexpress.com", 
                                          //            "genuine1", Mensaje, (String) c[2], "Paquete Disponible");
                                        UName = (String) Cliente2[0];
                                        UMail = (String) Cliente2[2];
                                        
                                    Send = SendMail.SendMail("paqueteria@genuinexpress.com", 
                                                      "genuine1", Mensaje(Cliente2,Articulo), (String) Cliente2[2], "Paquete Disponible");
                                }
                                if(Send){
                                    JOptionPane.showMessageDialog(null, "Articulo Registrado \n"
                                                                      + " se envio un correo a: "+UName+" \n"
                                                                      + "Al Mail: "+UMail);
                                }else{
                                    JOptionPane.showMessageDialog(null, "Articulo Registrado \n"
                                                                       +"NO SE ENVIO EL CORREO");  
                                }
                        }else if( jTable1.getValueAt(jTable1.getSelectedRow(), 7).equals("")){
                            if(JOptionPane.showConfirmDialog(null, "Seguro Desea Despachar")==0)
                                DBDataUpdate(ArticleTable, "Fecha_Salida = '"+dateFormat.format(new Date())+"',"
                                                        + "Estado = 'Entregado'", "'"+Warehouse.getText()+"'");
                        }else{
                            JOptionPane.showMessageDialog(null,"Este Articulo ya fue despachado");
                        }
                    }else{
                        JOptionPane.showMessageDialog(null,"Este Articulo no esta registrado");
                    }
                }
                Limpiar(jTable1, Filtro, BarCode, Warehouse, Cliente, Descripcion, Peso, Paquetes, Buscar);
            }
    }

    public static void GetFromtable(JTable jTable1,JTextField Warehouse,
                                    JTextField Cliente,JTextField Descripcion,JTextField Peso,
                                    JTextField Paquetes,JTextField BarCode){
        Warehouse.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 1)));
        Cliente.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 2)));
        Descripcion.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 3)));
        Peso.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 4)));
        Paquetes.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 5)));
        BarCode.setText(String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(), 8)));
    }

    public static void GetReg ( JTable  Tabla){    
        GetRegister(ArticleTable+" WHERE eSTADO like '%Almacen%' order by fecha desc LIMIT 500", Tabla,ColmNames);
    }

    private static String Mensaje(Object[] Cliente, Object[] Articulo) {
        return "<html><style>\n" +
                                                "	.top{\n" +
                                                "		border-top:solid #ff0000;\n" +
                                                "	}\n" +
                                                "	\n" +
                                                "	td{\n" +
                                                "		width: 200px;\n" +
                                                "	}"+
                                                "table{\n" +
                                                "		color: blue;\n" +
                                                "		font: oblique bold 100%;\n" +
                                                "	}\n" +
                                                "</style>\n" +
                                                "<table>\n" +
                                                "	<tr >\n" +
                                                "		<td colspan=\"2\" height=\"50px\">Estimado cliente.</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr>\n" +
                                                "		<td colspan=\"2\" height=\"50px\">Usted Ha Recibido el siguiente paquete en nuestro Almacen</td>\n" +
                                                "	</tr>\n" +
                                                "\n" +
                                                "	<tr>\n" +
                                                "		<td>Codigo GP:</td>\n" +
                                                "		<td>"+Cliente[4]+"</td>\n" +
                                                "	</tr>\n" +
                                                "\n" +
                                                "	<tr>\n" +
                                                "		<td>A nombre de:</td>\n" +
                                                "		<td class=\"top\">"+Cliente[0]+"</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr>\n" +
                                                "		<td>No. de WR:</td>\n" +
                                                "		<td class=\"top\">"+Articulo[1]+"</td>\n" +
                                                "	</tr>\n" +
                                                "	<tr>\n" +
                                                "		<td>Contenido:</td>\n" +
                                                "		<td class=\"top\">"+Articulo[10]+"</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr>\n" +
                                                "		<td>Tracking:</td>\n" +
                                                "		<td class=\"top\">"+Articulo[3]+"</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr>\n" +
                                                "		<td>Peso:</td>\n" +
                                                "		<td class=\"top\">"+Articulo[9]+"  Lb.</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
      //                                          "	<tr>\n" +
    //                                            "		<td>Monto A Pagar:</td>\n" +
  //                                              "		<td class=\"top\">Monto</td>\n" +
//                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr>\n" +
                                                "		<td></td>\n" +
                                                "		<td class=\"top\"></td>\n" +
                                                "	</tr>\n" +
                                                "	<tr>\n" +
                                                "		<td colspan=\"2\" align=\"center\">\n" +
                                                "			<img src=\"http://genuinexpress.com/media/media/images/GenuineLogoH.png\" width=\"300\" height=\"140\">\n" +
                                                "		</td>\n" +
                                                "	</tr>\n" +
                                                "	\n" +
                                                "	<tr >\n" +
                                                "		<td colspan=\"2\" align=\"center\">\n" +
                                                "			<font face=\"Bradley Hand ITC\" color=\"blue\" size=\"5\" >		\n" +
                                                "				Tel. 809-566-9445\n" +
                                                "			</font>\n" +
                                                "		</td>\n" +
                                                "	</tr>\n" +
                                                "	<tr >\n" +
                                                "		<td colspan=\"2\" align=\"center\">\n" +
                                                "			<font face=\"Bradley Hand ITC\" color=\"blue\" size=\"5\">\n" +
                                                "				Ext. 235 / 236 / 239 / 240\n" +
                                                "			</font>\n" +
                                                "		</td>\n" +
                                                "	</tr>\n" +
                                                "</table></html>";
    }
           
    public static void BuscarUpdate(JComboBox Filtro,JTextField Buscar,
                                    JTable jTable1,JTextField Warehouse,
                                    JTextField Cliente,JTextField Descripcion,
                                    JFormattedTextField Peso,JTextField Paquetes,
                                    JTextField BarCode){
        if((Filtro.getSelectedIndex() == 0 && !Buscar.getText().isEmpty())){
                Buscar( jTable1, Buscar, Filtro,Warehouse,Cliente,Descripcion,Peso,Paquetes,BarCode);
        }
    }
    
    public static void BuscarPressed(KeyEvent evt,JComboBox Filtro,JTextField Buscar,
                                     JTable jTable1,JTextField Warehouse,
                                     JTextField Cliente,JTextField Descripcion,
                                     JFormattedTextField Peso,JTextField Paquetes,
                                     JTextField BarCode) {                                  
        if(evt.getKeyCode()== 10){
            Buscar( jTable1, Buscar, Filtro,Warehouse,Cliente,Descripcion,Peso,
                    Paquetes,BarCode);
        }else if(evt.getKeyCode() == 27){
            Limpiar(jTable1, Filtro, BarCode, Warehouse, Cliente, Descripcion, 
                    Peso, BarCode, Buscar);
        }
    }
    
    public static void GuardarPressed(KeyEvent evt,JComboBox Filtro,JTextField Buscar,
                                     JTable jTable1,JTextField Warehouse,
                                     JTextField Cliente,JTextField Descripcion,
                                     JFormattedTextField Peso,JTextField Paquetes,
                                     JTextField BarCode) {                                   
        if(evt.getKeyCode()== 10){
            Guardar( jTable1, Warehouse, Cliente, Descripcion, Peso, 
                        Paquetes, BarCode,Filtro,Buscar);
        }
    } 
}
